package com.spatio.serving.basic.service.template.core.component.invoker;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.spatio.serving.basic.service.template.common.domain.*;
import com.spatio.serving.basic.service.template.common.req.UserDateBaseReq;
import com.spatio.serving.basic.service.template.mysql.mapper.MealMapper;
import com.spatio.serving.basic.service.template.mysql.mapper.UserMapper;
import com.spatio.serving.common.lib.common.util.JsonUtil;
import com.spatio.serving.common.lib.common.util.LatencyWatch;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.time.LocalDate;
import java.util.List;


@Component
public class createUserDocInvoker {
    public static final String TOKEN_BEARER = "Bearer ";

    @Autowired
    private MealMapper mealMapper;
    @Autowired
    private UserMapper userMapper;

    @Value("${dify_user_database_id}")
    private String dataset_id;

    @Value("${dify_user_doc_token}")
    private String user_doc_token;

    @Value("${dify_ceate_doc_url}")
    private String create_url;
    @Value("${dify_update_doc_url}")
    private String update_url;

    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout(5000)
            .setConnectTimeout(5000)
            .setSocketTimeout(13000)
            .setCookieSpec(CookieSpecs.STANDARD)
            .build();

    public boolean createOrUpdateDoc(BigInteger user_id) throws IOException {
        String user_doc_id =mealMapper.queryUserDocId(user_id);
        boolean flag = true;
        if (user_doc_id==null){
                String docId=createDoc(user_id);
                flag=userMapper.updateDocId(user_id,docId);
        }else {
                String docId=userMapper.queryDocId(user_id);
                flag=updateDoc(user_id,docId);
        }
        return flag;
    }

    private String createDoc(BigInteger user_id) throws IOException {
        String url = create_url.replace("{dataset_id}", dataset_id);
        HttpResponse response;
        List<mutliFoodRecordDo>foodRecordDos=getUserHistoryRecord(user_id);
        JSONObject processRule = new JSONObject();
        processRule.put("mode", "automatic");
        JSONObject req = new JSONObject();
        req.put("name", String.valueOf(user_id));
        req.put("text", String.valueOf(foodRecordDos));
        req.put("indexing_technique", "economy");
        req.put("process_rule",processRule);
        HttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();
        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(req.toString());
        httpPost.setEntity(entity);
        httpPost.setHeader("Authorization", TOKEN_BEARER + user_doc_token);
        httpPost.setHeader("Content-Type", "application/json");
        response = httpClient.execute(httpPost);
        String responseBody = EntityUtils.toString(response.getEntity());
        JSONObject res = JsonUtil.fromJson(responseBody, JSONObject.class);
        String id = res.getJSONObject("document").getString("id");
        return id;
    }

    private boolean updateDoc(BigInteger user_id , String docId) throws IOException {
        String url_temp = update_url.replace("{dataset_id}", dataset_id);
        String url = url_temp.replace("{document_id}", docId);
        HttpResponse response;
        List<mutliFoodRecordDo>foodRecordDos=getUserHistoryRecord(user_id);
        JSONObject processRule = new JSONObject();
        processRule.put("mode", "automatic");
        JSONObject req = new JSONObject();
        req.put("name", String.valueOf(user_id));
        req.put("text", String.valueOf(foodRecordDos));
        HttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();
        HttpPost httpPost = new HttpPost(url);

        StringEntity entity = new StringEntity(req.toString(),"utf-8");
        httpPost.setEntity(entity);
        httpPost.setHeader("Authorization", TOKEN_BEARER + user_doc_token);
        httpPost.setHeader("Content-Type", "application/json");
        response = httpClient.execute(httpPost);
        //String responseBody = EntityUtils.toString(response.getEntity());
        //JSONObject res = JsonUtil.fromJson(responseBody, JSONObject.class);
        //String id = res.getJSONObject("document").getString("id");
        if (response == null || response.getStatusLine().getStatusCode() != 200){
            return false;
        }else{
            return true;
        }
    }

    private List<mutliFoodRecordDo> getUserHistoryRecord(BigInteger user_id){
        List<mutliFoodRecordDo> res = mealMapper.getRecordForDoc(user_id);
        return res;
    }

}
